package com.example.networktest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;

import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        if(v.getId() == R.id.send_request){
//            sendRequestWithHttpURLConnection();
            sendRequestWithOkHttp();
        }
    }

//    private void sendRequestWithHttpURLConnection() {
//        // 开启线程来发起网络请求
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                HttpURLConnection connection = null;
//                BufferedReader reader = null;
//                try{
//                    URL url = new URL("http://www.baidu.com");
//                    connection = (HttpURLConnection) url.openConnection();
//                    connection.setRequestMethod("GET");
//                    connection.setConnectTimeout(8000);
//                    connection.setReadTimeout(8000);
//                    InputStream in = connection.getInputStream();
//
//                    // 下面对获得到的输入流进行读取
//                    reader = new BufferedReader(new InputStreamReader(in));
//                    StringBuilder response = new StringBuilder();
//                    String line;
//                    while ((line = reader.readLine()) != null){
//                        response.append(line);
//                    }
//                    showResponse(response.toString());
//                } catch (Exception e){
//                    e.printStackTrace();
//                } finally {
//                    if(reader != null){
//                        try {
//                            reader.close();
//                        } catch (IOException e){
//                            e.printStackTrace();
//                        }
//                    }
//                    if (connection != null){
//                        connection.disconnect();
//                    }
//                }
//            }
//        }).start();
//    }
    
    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://10.0.2.2/get_data.xml")  // get_data.json
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
//                    showResponse(responseData);
//                    parseXMLWithSAX(responseData);
                    parseJSONWithGSON(responseData);
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // Apache 中创建 xml 的文件并在Android项目发起请求解析xml文件
//    private void sendRequestWithOkhttp() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try{
//                    OkHttpClient client = new OkHttpClient();
//                    Request request = new Request.Builder()
//                            // 指定访问的服务器地址是电脑本机
//                            .url("http://10.0.2.2/get_data.xml")
//                            .build();
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    parseXMLWithPull(responseData);
//                } catch (Exception e){
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }

//    private void parseXMLWithPull(String xmlData){
//        try{
//            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
//            XmlPullParser xmlPullParser = factory.newPullParser();
//            xmlPullParser.setInput(new StringReader(xmlData));
//            int eventType = xmlPullParser.getEventType();
//            String id = "";
//            String name = "";
//            String version = "";
//            while(eventType != XmlPullParser.END_DOCUMENT){
//                String nodeName = xmlPullParser.getName();
//                switch (eventType){
//                    // 开始解析某个节点
//                    case XmlPullParser.START_TAG:{
//                        if("id".equals(nodeName)){
//                            id = xmlPullParser.nextText();
//                        } else if("name".equals(nodeName)){
//                            name = xmlPullParser.nextText();
//                        } else if("version".equals(nodeName)){
//                            version = xmlPullParser.nextText();
//                        }
//                        break;
//                    }
//                    // 完成解析某个节点
//                    case XmlPullParser.END_TAG:{
//                        if("app".equals(nodeName))}{
//                        Log.d("MainActivity","id is" + id);
//                        Log.d("MainActivity","name is" + name);
//                        Log.d("MainActivity","version is" + version);
//                    }
//                    break;
//                }
//                default:
//                    break;
//            }
//            eventType = xmlPullParser.next();
//            }
//        } catch (Exception e){
//        e.printStackTrace();
//        }
//    }

//    private void parseXMLWithSAX(String xmlData){
//        tyr{
//            SAXParserFactory factory = SAXParserFactory.newInstance();
//            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
//            ContentHandler handler = new ContentHandler();
//            // 将 ContentHandler 实例设置到 XMLReader
//            xmlReader.setContentHandler(handler);
//            // 开始执行解析
//            xmlReader.parse(new InputStream(new StringReader(xmlData)));
//        } catch(Exception e){
//            e.printStackTrace();
//        }
//    }

    private void parseJSONWithGSON(String jsonData){
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
        for (App app : appList){
            Log.d("MainActivity","id is" + app.getId());
            Log.d("MainActivity","name is" + app.getName());
            Log.d("MainActivity","version is" + app.getVersion());
        }
    }

}